package com.erp.erp_ui.Customer;

import com.alibaba.fastjson.JSONObject;
import com.erp.erp_entitys.Customer.CustomerAndEmail;
import com.erp.erp_entitys.Customer.CustomerEntity;
import com.erp.erp_entitys.Customer.CustomerExample;
import com.erp.erp_entitys.Customer.CustomerVoEntity;
import com.erp.erp_entitys.Customer.*;
import com.erp.erp_entitys.CustomerAutoPool.CustomerAutoPool;
import com.erp.erp_entitys.CustomerAutoPool.CustomerAutoPoolExample;
import com.erp.erp_entitys.CustomerContact.CustomerContactEntity;
import com.erp.erp_entitys.CustomerContact.CustomerContactExample;
import com.erp.erp_entitys.CustomerLog.CustomerLogEntity;
import com.erp.erp_entitys.CustomerPool.CustomerPoolEntity;
import com.erp.erp_entitys.CustomerPool.CustomerPoolExample;
import com.erp.erp_entitys.CustomerShare.CustomerShareEntity;
import com.erp.erp_entitys.CustomerShare.CustomerShareExample;
import com.erp.erp_entitys.Dictionary.DictionaryEntity;
import com.erp.erp_entitys.Email.email_email;
import com.erp.erp_entitys.Message.MessageExample;
import com.erp.erp_entitys.ProcessCustomer.ProcessCustomerEntity;
import com.erp.erp_entitys.ProcessCustomer.ProcessCustomerExample;
import com.erp.erp_entitys.User.UserEntity;
import com.erp.erp_entitys.User.UserEntityExample;
import com.erp.erp_entitys.business.entity.ExportContractEntity;
import com.erp.erp_servers.Customer.ICustomerService;
import com.erp.erp_servers.CustomerAutoPool.ICustomerAutoPoolService;
import com.erp.erp_servers.CustomerContact.imp.ImpCustomerContactService;
import com.erp.erp_servers.CustomerLog.ICustomerLogService;
import com.erp.erp_servers.CustomerPool.ICustomerPoolService;
import com.erp.erp_servers.CustomerShare.ICustomerShareService;
import com.erp.erp_servers.Dictionary.IDictionary2Service;
import com.erp.erp_servers.Email.EmailService;
import com.erp.erp_servers.ProcessCustomer.IProcessCustomerService;
import com.erp.erp_servers.User.IUserService;
import com.erp.erp_servers.business.IExportContractService;
import com.erp.erp_ui.Activiti.ProcessService;
import com.erp.erp_ui.Message.req.EditMessageReq;
import com.erp.erp_ui.Message.service.MessageAllService;
import com.erp.erp_ui.base.Base;
import com.erp.utils.DateUtils;
import com.erp.utils.R;
import com.erp.utils.ResultStatusEnum;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 客户
 * @ClassName CustomerControl
 * @Description TODO
 * @Author songjizhen
 * @Date 2020-07-03 23:07
 * @Version 1.0
 */
@Controller
@RequestMapping(value = "customer")
public class CustomerControl extends Base {
    @Autowired
    ICustomerService customerService;
    @Autowired
    IUserService userService;
    @Autowired
    ICustomerPoolService customerPoolService;
    @Autowired
    ICustomerLogService customerLogService;
    @Autowired
    ICustomerShareService customerShareService;
    @Autowired
    IProcessCustomerService processCustomerService;
    @Autowired
    ICustomerAutoPoolService customerAutoPoolService;
    @Autowired
    ImpCustomerContactService customerContactService;
    @Autowired
    IExportContractService exportContractService;
    /**
     * 消息接口
     */
    @Autowired
    MessageAllService messageAllService;

    /**
     * 邮件接口
     */
    @Autowired
    EmailService emailService;

    /**
     * 字典接口
     */
    @Autowired
    IDictionary2Service dictionary2Service;

    /**
     * 获了当前登陆者所管理的客户信息
     * @param
     * @return
     */
    @RequestMapping(value = "selectByPage")
    @ResponseBody
    public  R<List<CustomerVoEntity>> selectByPage(String name, String type, String saleman,String flag,String type2,String sourceOfCustomers, String attributesOfCustomers,String isMaker){
        try{
            UserEntity user = (UserEntity)this.getBean("user");
            String cr=user.getCustomerRole();
            if(saleman.equals("")){
                saleman=user.getCustomerRole();
            }
            //判断是否是全选
           String s1=saleman.replaceAll(",","");
            String s2=cr.replaceAll(",","");
            if(s1.length()==s2.length()){
                if (StringUtils.isNotBlank(saleman)){
                    saleman=saleman+","+user.getCode();
                }else {
                    saleman=user.getCode();
                }
            }
            /////////////////////////////////////////
            //如果是从控制台跳转来的
            if(StringUtils.isNotEmpty(flag) && flag.equals("kzt")){
                /*List<String> likzt=new ArrayList<>();
                Map<String, Object> hz = customerService.getHZ2(user);
                long total=0;
                switch (type){
                    case "1"://本月新增
                        List<CustomerEntity> list=(List<CustomerEntity>)hz.get("newCustomer");
                        total=Long.parseLong(hz.get("newCustomerCount").toString());
                        if(list.size()==0){
                            return R.build(null);
                        }else{
                            likzt=this.getCustomerByKzt(list);
                        }
                        break;
                    case "2":
                        likzt=(List<String>) hz.get("contact30");
                        total=Long.parseLong(hz.get("contact30Count").toString());
                        break;
                    case "4":
                        likzt=(List<String>) hz.get("contact60");
                        total=Long.parseLong(hz.get("contact60Count").toString());
                        break;
                    default:
                        likzt=(List<String>) hz.get("contact85");
                        total=Long.parseLong(hz.get("contact85Count").toString());
                }*/
                List<CustomerEntity> customerEntities=null;
                       //时间
                        Map<String, Object> map=new HashMap<>();
                        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                        //获取当前月第一天：
                        Calendar c = Calendar.getInstance();
                        c.add(Calendar.MONTH, 0);
                        c.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天
                        String first = format.format(c.getTime());
                        //获取当前月最后一天
                        Calendar ca = Calendar.getInstance();
                        ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
                        String last = format.format(ca.getTime());

                switch (type2){
                    case "1"://本月新增
                        CustomerExample example=new  CustomerExample();
                        CustomerExample.Criteria criteria = example.createCriteria();
                        criteria.andCreatetimeBetween(c.getTime(),ca.getTime());
                        criteria.andSalesmanIn(Arrays.asList(saleman.split(",")));
                        customerEntities=customerService.selectByExample(example);
                        break;
                    case "2":
                        customerEntities=customerService.selectByKzt("30",saleman,name,type);
                        break;
                    case "3":
                        customerEntities=customerService.selectByKzt("60",saleman,name,type);
                        break;
                    case "4":
                        customerEntities=customerService.selectByKzt("85",saleman,name,type);
                        break;
                    default:
                       // customerEntities=customerService.selectByKzt("",saleman,name,type);

                }
                /*CustomerExample examplekzt=new CustomerExample();
                CustomerExample.Criteria criteriakzt = examplekzt.createCriteria();
                criteriakzt.andCodeIn(likzt);
                List<CustomerEntity> customerEntities = customerService.selectByExample(examplekzt);*/
               /* if(customerEntities.size()>10){
                    for (int i=10;i<customerEntities.size();i++){
                        customerEntities.remove(i);
                    }
                }*/
                long total=0;
                R<List<CustomerEntity>> build = R.build(customerEntities);
                total=build.getTotal();
                List<Integer> li=new ArrayList<>();
                Map<String,String> map2=userService.selectAll();
                for(int i=0;i<customerEntities.size();i++){
                    CustomerEntity customers = customerEntities.get(i);
                    customers.setSalesman(map2.get(customers.getSalesman()));
                    li.add(customers.getId());
                }

                ProcessCustomerExample example=new ProcessCustomerExample();
                ProcessCustomerExample.Criteria criteria = example.createCriteria();
                criteria.andCustomeridIn(li);
                List<ProcessCustomerEntity> processCustomerEntities = processCustomerService.selectByExample(example);
                Map<Integer,String> pmp=new HashMap<>();
                for(int i=0;i<processCustomerEntities.size();i++){
                    pmp.put(processCustomerEntities.get(i).getCustomerid(),processCustomerEntities.get(i).getProcessid());
                }
                List<CustomerVoEntity> list=new ArrayList<>();
                for(int i=0;i<customerEntities.size();i++){
                    CustomerVoEntity vo=new CustomerVoEntity();
                    vo=vo.conver(customerEntities.get(i));
                    vo.setProcessid(pmp.get(vo.getId()));
                    list.add(vo);
                }
                R<List<CustomerVoEntity>> build1 =R.build(list);
                build1.setTotal(total);
                build1.setCount(total);
                build1.setStatus(200);
                build1.setCode(0);
                return build1;
            }

//            String codes=" SELECT REPLACE(CODE,'\"','') CODE  FROM  customer_share WHERE usercode LIKE '%"+user.getCode()+"%' AND TYPE=1";
            if(name==null){
                name="";
            }
            if(type==null) type="";
            if(saleman==null) saleman="";
//            Map mp=new HashMap<>();
//            mp.put("name",name);
//            mp.put("type",type);
            CustomerEntity ce=new CustomerEntity();
            ce.setName(name);
            ce.setType(type);
            //String salesman="";

            //salesman=user.getCode();
           /* CustomerExample example=new CustomerExample();
            CustomerExample.Criteria criteria = example.createCriteria();*/
            //if(! isAdmin(user)){//不是管理员
                // codes=getcodes(user.getCode());
              //  ce.setSalesman(user.getCode());

            //}else{
                ce.setSalesman(saleman);
            //}
//            ce.setCode(codes);
           /* criteria.andNameLike("%"+name+"%");
            criteria.andTypeLike("%"+type+"%");*/

            ce.setAttributesOfCustomers(attributesOfCustomers);
            ce.setSourceOfCustomers(sourceOfCustomers);
            ce.setCustomerShareUserCode(user.getCode());
            ce.setIsMaker(isMaker);

            List<CustomerEntity> customerEntities =customerService.selectByMap(ce);// customerService.selectByExample(example);
            R<List<CustomerEntity>> build = R.build(customerEntities);
            List<Integer> li=new ArrayList<>();
            Map<String,String> map=userService.selectAll();
            for(int i=0;i<customerEntities.size();i++){
                CustomerEntity customers = customerEntities.get(i);
                customers.setSalesman(map.get(customers.getSalesman().replaceAll("\r|\n", "")));
                li.add(customers.getId());
            }


            ProcessCustomerExample example=new ProcessCustomerExample();
            ProcessCustomerExample.Criteria criteria = example.createCriteria();
            if (li.size()>0){
                criteria.andCustomeridIn(li);
            }
            List<ProcessCustomerEntity> processCustomerEntities = processCustomerService.selectByExample(example);
            Map<Integer,String> pmp=new HashMap<>();
            for(int i=0;i<processCustomerEntities.size();i++){
                pmp.put(processCustomerEntities.get(i).getCustomerid(),processCustomerEntities.get(i).getProcessid());
            }
            List<CustomerVoEntity> list=new ArrayList<>();
            for(int i=0;i<customerEntities.size();i++){
                CustomerVoEntity vo=new CustomerVoEntity();
                vo=vo.conver(customerEntities.get(i));
                vo.setProcessid(pmp.get(vo.getId()));

                //添加客户属性
                if (StringUtils.isNotEmpty(customerEntities.get(i).getAttributesOfCustomers())){
                    DictionaryEntity dictionaryEntity = dictionary2Service.selectByParam(1, 87, customerEntities.get(i).getAttributesOfCustomers());
                    if (dictionaryEntity!=null){
                        vo.setAttributesOfCustomers(dictionaryEntity.getName());
                    }
                }
                list.add(vo);
            }

            R<List<CustomerVoEntity>> build1 = R.build(list);
            build1.setMsg(build.getMsg());
            build1.setStatus(build.getStatus());
            build1.setCount(build.getCount());
            build1.setCode(build.getCode());
            build1.setTotal(build.getTotal());
            return build1;
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     *
     * @param name  客户名称
     * @param type   客户类型
     * @param saleman  所属业务员
     * @return
     */
    @RequestMapping(value = "queryByPage")
    @ResponseBody
    public R<List<CustomerEntity>> queryByPage(String name, String type, String saleman){

        try {
            CustomerExample example=new CustomerExample();
            CustomerExample.Criteria criteria = example.createCriteria();
            List<String> listType=getList(type);
            if(listType.size()>0){
                criteria.andTypeIn(listType);
            }
            List<String> listSaleman=getList(saleman);
            if(listSaleman.size()>0){
                criteria.andSalesmanIn(listSaleman);
            }
            if(StringUtils.isNotEmpty(name)){
                criteria.andNameLike(""+name+"");
            }
            List<CustomerEntity> customerEntities = customerService.selectByExample(example);
            return R.build(customerEntities);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }

    }


    private List<String> getList(String data){
        List<String> list=new ArrayList<>();
        if(StringUtils.isNotEmpty(data)){
            String[] types=data.split(",");

            for(String ty:types){
                list.add(ty);
            }

        }
        return list;
    }

     private List<String> getCustomerByKzt(List<CustomerEntity> list){
        List<String> li=new ArrayList<>();
        for(int i=0;i<list.size();i++){
            li.add(list.get(i).getCode());
        }
        return li;
     }

    /**
     * 公共池
     * @return
     */
    @RequestMapping(value = "select3ByPage")
    @ResponseBody
    public R<List<CustomerEntity>> select3ByPage(String name,String type){
        try{

          /*  //根据code获取客户
            CustomerExample example2=new CustomerExample();
            CustomerExample.Criteria criteria2 = example2.createCriteria();
            //criteria2.andCodeIn(list);
            criteria2.andNameLike("%"+name+"%");
            criteria2.andCodeLike("%"+name+"%");
            criteria2.andAbbreviationLike("%"+name+"%");
            List<String> list=new ArrayList<>();
            if(!type.equals("")){
                String[] split = type.split(",");
                for(int i=0;i<split.length;i++){
                    list.add(split[i]);
                }
                criteria2.andTypeIn(list);
            }

             criteria2.andSalesmanEqualTo("");
            List<CustomerEntity> customerEntities = customerService.selectByExample(example2);*/
            UserEntity user = (UserEntity) this.getBean("user");
            CustomerEntity record=new CustomerEntity();
            record.setName(name);
            record.setType(type);
            record.setCreater(user.getCode());
            List<CustomerEntity> select = customerService.select(record);
            for (CustomerEntity p:select){
                //客户联系人
                CustomerContactExample example2=new CustomerContactExample();
                CustomerContactExample.Criteria criteria1 = example2.createCriteria();
                criteria1.andCompanyEqualTo(p.getCode());
                List<CustomerContactEntity> customerContactEntities = customerContactService.selectByExample(example2);
                List<String> emailList=customerContactEntities.stream().map(d -> d.getEmail()).collect(Collectors.toList());
                String email=emailList.stream().collect(Collectors.joining(", "));
                p.setEmailStr(email);
            }
            return R.build(select);
        }catch (Exception e){
        e.printStackTrace();
        return R.buildError(ResultStatusEnum.ERROR);
    }
    }

    /**
     * 客户汇总、供应商汇总
     * @return
     */
    @RequestMapping(value = "getByxzkh")
    @ResponseBody
    public R<Map<String, Object>> getByxzkh(){
        try {
            UserEntity user = (UserEntity)this.getBean("user");
            Map<String, Object> hz = customerService.getHZ(user);
            return R.build(hz);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }
    /**
     * 批量删除
     * @param ids
     * @return
     */
    @RequestMapping(value = "delete",method = RequestMethod.POST)
    @ResponseBody
    public R<Integer> delete(String[] ids){
        try {
            List<Integer> list=new ArrayList<>();
            for(int i=0;i<ids.length;i++){
                list.add(Integer.parseInt(ids[i].replace("[","").replace("]","")));
            }
            CustomerExample example=new CustomerExample();
            CustomerExample.Criteria criteria = example.createCriteria();
            criteria.andIdIn(list);
            List<CustomerEntity> customerEntities = customerService.selectByExample(example);
            int num = customerService.deleteByExample(example,  list);
            if(num ==0){
                return R.build(num);
            }
//删除公共池

            List<String> pools=new ArrayList<>();
            String codes="";//客户编码
            for(int i=0;i<customerEntities.size();i++){
                pools.add(customerEntities.get(i).getCode());
                codes+=   customerEntities.get(i).getCode()+",";
            }
            CustomerPoolExample poolExample=new CustomerPoolExample();
            CustomerPoolExample.Criteria criteria1 = poolExample.createCriteria();
            criteria1.andCodeIn(pools);
            num=customerPoolService.deleteByExample(poolExample);
            //日志
            UserEntity user = (UserEntity)this.getBean("user");

            List<String> listCode = customerEntities.stream().map(p -> p.getCode()).collect(Collectors.toList());

            //删除消息
            for (int i = 0; i <listCode.size() ; i++) {
                MessageExample messageExample=new MessageExample();
                MessageExample.Criteria messageExampleCriteria = messageExample.createCriteria();
                messageExampleCriteria.andContentLike("%"+listCode.get(i)+"%");
                messageExampleCriteria.andThemeEqualTo("客户待审批");
                messageAllService.delMessageByMessage(messageExample);
            }

            CustomerLogEntity record=new CustomerLogEntity();
            record.setCode(codes);
            record.setType("删除");
            record.setOptioner(user.getCode());
            record.setOptionTime(DateUtils.format(new Date()));
            record.setContent("客户编码："+codes);
            customerLogService.insert(record);

            return R.build(num);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 根据id获取客户
     * @param id
     * @return
     */
    @RequestMapping(value = "selectByKey")
    @ResponseBody
    public R<CustomerEntity> selectByKey(Integer id){
        try{
            CustomerEntity customerEntity = customerService.selectByPrimaryKey(id);
            //UserEntity userEntity = userService.selectUserByCode(customerEntity.getSalesman());
            //customerEntity.setSalesman(userEntity.getName());
            return R.build(customerEntity);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }
    /**
     * 根据code获取客户
     * @param code
     * @return
     */
    @RequestMapping(value = "getCustomerByCode")
    @ResponseBody
    public R selectByKey(String code){
        try{
            CustomerEntity customerEntity = customerService.findCustomerByCode(code);
            return R.build(customerEntity);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }



    @RequestMapping(value = "selectUserNameByUserCode")
    @ResponseBody
    public R<String> selectUserNameByUserCode(String code){
        try{
           // CustomerEntity customerEntity = customerService.selectByPrimaryKey(id);
            UserEntity userEntity = userService.selectUserByCode(code);
            //customerEntity.setSalesman(userEntity.getName());
            return R.build(userEntity.getName());
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }
    /**
     * 根据主键更新
     * @param record
     * @return
     */
    @RequestMapping(value = "updateByKey",method = RequestMethod.POST)
    @ResponseBody
    public R<Integer> updateByKey(@RequestBody CustomerEntity record){
        try{
            int num = customerService.updateByPrimaryKeySelective(record);
            //日志
            UserEntity user = (UserEntity)this.getBean("user");
            CustomerLogEntity log=new CustomerLogEntity();
            log.setCode(record.getCode());
            log.setType("更新");
            log.setOptioner(user.getCode());
            log.setOptionTime(DateUtils.format(new Date()));
            log.setContent("客户编码："+record.getCode());
            customerLogService.insert(log);
            return R.build(num);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }
    @RequestMapping(value = "updateHByKey" )
    @ResponseBody
    public R<Integer> updateHByKey( String id,String status){
        try{
            CustomerEntity record=new CustomerEntity();
            record.setId(Integer.parseInt(id));
            record.setStatus(status);
            int num = customerService.updateByPrimaryKeySelective(record);
            //日志
            UserEntity user = (UserEntity)this.getBean("user");
            CustomerLogEntity log=new CustomerLogEntity();
            log.setCode(record.getCode());
            log.setType("更新");
            log.setOptioner(user.getCode());
            log.setOptionTime(DateUtils.format(new Date()));
            log.setContent("客户编码："+record.getCode());
            customerLogService.insert(log);
            return R.build(num);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 加入公共池，先更新客户表，再更新公共池表
     * @param ids
     * @return
     */
    @RequestMapping(value = "update",method = RequestMethod.POST)
    @ResponseBody
    public  R<Integer> update(String[] ids){
        try {
            UserEntity user = (UserEntity)this.getBean("user");
            List<Integer> list=new ArrayList<>();
            for(int i=0;i<ids.length;i++){
                list.add(Integer.parseInt(ids[i].replace("[","").replace("]","")));
            }
            CustomerEntity record=new CustomerEntity();
            record.setSalesman("");
            CustomerExample example=new CustomerExample();
            CustomerExample.Criteria criteria = example.createCriteria();
            criteria.andIdIn(list);
            int num = customerService.updateByExampleSelective(record,example);

            record.setUpdater(user.getCode());
            record.setUpdatetime(new Date());
            customerService.updateByPrimaryKey(record);

            List<CustomerEntity> customerEntities = customerService.selectByExample(example);
            List<String> poollist=new ArrayList<>();
            String codes="";
            for(int i=0;i<customerEntities.size();i++){
                poollist.add(customerEntities.get(i).getCode());
                codes+=customerEntities.get(i).getCode()+",";
            }
            //更新公共池
            CustomerPoolExample poolExample=new CustomerPoolExample();
            CustomerPoolExample.Criteria criteria1 = poolExample.createCriteria();
            criteria1.andCodeIn(poollist);
            CustomerPoolEntity recordpool=new CustomerPoolEntity();
            recordpool.setSalesman("");
            num = customerPoolService.updateByExampleSelective(recordpool, poolExample);
            //日志
            CustomerLogEntity log=new CustomerLogEntity();
            log.setCode(codes);
            log.setType("加入公共池");
            log.setOptioner(user.getCode());
            log.setOptionTime(DateUtils.format(new Date()));
            log.setContent("客户编码："+codes);
            customerLogService.insert(log);
            return R.build(num);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 设为自己
     * @param ids
     * @return
     */
    @RequestMapping(value = "setself",method = RequestMethod.POST)
    @ResponseBody
    public R<Integer> setself(String[] ids){
        try{
            UserEntity user = (UserEntity)this.getBean("user");
            List<Integer> list=new ArrayList<Integer>();
            for(int i=0;i<ids.length;i++){
                list.add(Integer.parseInt(ids[i].replace("[","").replace("]","")));
            }
            CustomerExample example=new CustomerExample();
            CustomerExample.Criteria criteria = example.createCriteria();
            criteria.andIdIn(list);
            CustomerEntity recode=new CustomerEntity();
            recode.setSalesman(user.getCode());
            recode.setUpdater(user.getCode());
            recode.setUpdatetime(new Date());
            recode.setCreater(user.getCode());
            int num = customerService.updateByExampleSelective(recode, example);


           // customerService.updateByPrimaryKey(recode);
          //num= customerService.updateByExampleSelective(recode,example);

            List<CustomerEntity> customerEntities = customerService.selectByExample(example);
            List<String> poollist=new ArrayList<>();
            String codes="";
            for(int i=0;i<customerEntities.size();i++){
                poollist.add(customerEntities.get(i).getCode());
                codes+=customerEntities.get(i).getCode()+",";
            }
            //更新公共池
            //更新公共池
            CustomerPoolExample poolExample=new CustomerPoolExample();
            CustomerPoolExample.Criteria criteria1 = poolExample.createCriteria();
            criteria1.andCodeIn(poollist);
            num=customerPoolService.deleteByExample(poolExample);
           /* CustomerPoolEntity recordpool=new CustomerPoolEntity();
            recordpool.setSalesman(user.getCode());
            num = customerPoolService.updateByExampleSelective(recordpool, poolExample);*/

            //日志
            CustomerLogEntity log=new CustomerLogEntity();
            log.setCode(codes);
            log.setType("设为自己");
            log.setOptioner(user.getCode());
            log.setOptionTime(DateUtils.format(new Date()));
            log.setContent("客户编码："+codes);
            customerLogService.insert(log);
            return R.build(num);
        }catch (Exception e) {
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }

    }

    /**
     * 分配客户
     * @param ids
     * @param saleman
     * @return
     */
    @RequestMapping(value = "savefp",method = RequestMethod.POST)
    @ResponseBody
    public  R<Integer> savefp(String[] ids,String saleman){
        try{
            UserEntity user = (UserEntity)this.getBean("user");
            List<Integer> list=new ArrayList<Integer>();
            for(int i=0;i<ids.length;i++){
                list.add(Integer.parseInt(ids[i].replace("[","").replace("]","")));
            }
            CustomerExample example=new CustomerExample();
            CustomerExample.Criteria criteria = example.createCriteria();
            criteria.andIdIn(list);
            CustomerEntity recode=new CustomerEntity();
            recode.setSalesman(saleman);
            int num = customerService.updateByExampleSelective(recode, example);

            recode.setUpdatetime(new Date());
           recode.setUpdater(user.getCode());
            recode.setCreater(saleman);
           customerService.updateByPrimaryKey(recode);

            List<CustomerEntity> customerEntities = customerService.selectByExample(example);
            List<String> poollist=new ArrayList<>();
            String codes="";
            for(int i=0;i<customerEntities.size();i++){
                poollist.add(customerEntities.get(i).getCode());
                codes+=customerEntities.get(i).getCode()+",";
            }
            //更新公共池
            //更新公共池
            CustomerPoolExample poolExample=new CustomerPoolExample();
            CustomerPoolExample.Criteria criteria1 = poolExample.createCriteria();
            criteria1.andCodeIn(poollist);
            CustomerPoolEntity recordpool=new CustomerPoolEntity();
            recordpool.setSalesman(saleman);
            num = customerPoolService.updateByExampleSelective(recordpool, poolExample);
//日志

            CustomerLogEntity log=new CustomerLogEntity();
            log.setCode(codes);
            log.setType("分配客户");
            log.setOptioner(user.getCode());
            log.setOptionTime(DateUtils.format(new Date()));
            log.setContent("客户编码："+codes);
            customerLogService.insert(log);
        return R.build(num);
        }catch (Exception e) {
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }
    /**
     * 新增,同进插入公共池
     * @param record
     * @return
     */
    @RequestMapping(value = "insert",method = RequestMethod.POST)
    @ResponseBody
    public R<String> insert(@RequestBody CustomerEntity record){
        try{

            //检测 客户简码 重复
            Integer type=0;//type 1：新增 2：修改
            Integer id=record.getId();
            if (id !=null){
                type=2;
            }else {
                type=1;
            }
            String flag=isRepeat(id,record.getShortCode(),type);
            switch (flag){
                case "shortCode":
                    return R.buildCustomize(-100001,"客户简码重复");
            }

            UserEntity user = (UserEntity)this.getBean("user");

            //日志
            CustomerLogEntity log=new CustomerLogEntity();
            log.setCode(record.getCode());
            log.setOptioner(user.getCode());
            log.setOptionTime(DateUtils.format(new Date()));
            log.setContent("客户编码："+record.getCode());

            //返回值
            String codeStr="";

            //修改
            if (id !=null){
                //修改客户信息
                customerService.updateByPrimaryKeySelective(record);
                if(record.getSpstatus().equals("2")){
                    addMessageSp(record,user);
                }
                //日志
                log.setType("更新");
                customerLogService.insert(log);

                codeStr=record.getCode()+":"+record.getId();
            }else {//新增
                if(isExit(record.getCode())){
                    record.setCode(System.currentTimeMillis()+"");
                }
                record.setCreater(user.getCode());
                record.setCreatetime(new Date());
                record.setSalesman(user.getCode());

                //新增客户信息
                customerService.insertSelective(record);

                if(record.getSpstatus().equals("2")){
                    addMessageSp(record,user);
                }
                //插入公共池
                CustomerPoolEntity recordpool=new CustomerPoolEntity();
                recordpool.setSalesman(record.getSalesman());
                recordpool.setCode(record.getCode());
                customerPoolService.insert(recordpool);

                //日志
                log.setType("新增");
                customerLogService.insert(log);

                codeStr=getCode(record.getCode());
            }
            return R.build(codeStr);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 新增消息
     * 提交审批 添加到消息表，接收人为营销部门的总监(YXZJ003)
     */
    public void addMessageSp(CustomerEntity record, UserEntity user) throws ParseException {
        List<String> adminCode = messageAllService.getMarketingDirector();
        EditMessageReq req=new EditMessageReq();
        req.setTheme("客户待审批");
        req.setReceiverCode(StringUtils.join(adminCode,","));
        req.setMessageType(4);
        req.setContent("客户名称为："+record.getName()+
                "，客户简码为："+record.getShortCode()+
                "，客户编码为："+record.getCode()+
                "，客户简称为："+record.getAbbreviation());
        messageAllService.editMessage(req,user.getName(),user.getCode());
    }

    private  boolean isExit(String code){
        CustomerExample example=new CustomerExample();
        CustomerExample.Criteria criteria = example.createCriteria();
       criteria.andCodeEqualTo(code);
        List<CustomerEntity> customerEntities = customerService.selectByExample(example);
        return customerEntities.size()==0?false:true;
    }
    private  String getCode(String code){
        CustomerExample example=new CustomerExample();
        CustomerExample.Criteria criteria = example.createCriteria();
        criteria.andCodeEqualTo(code);
        List<CustomerEntity> customerEntities = customerService.selectByExample(example);
        return customerEntities.get(0).getCode()+":"+customerEntities.get(0).getId();
    }

    /**
     * 检测 客户简码 是否重复
     * @param shortCode 客户简码
     * @param type 1：新增 2：修改
     * @return
     */
    private String isRepeat(Integer id,String shortCode,Integer type){
        if (StringUtils.isNotEmpty(shortCode)){
            CustomerExample example=new CustomerExample();
            CustomerExample.Criteria criteria = example.createCriteria();
            criteria.andShortCodeEqualTo(shortCode);
            List<CustomerEntity> list = customerService.selectByExample(example);
            if (list.size()>0){
                if (type==1){
                    return "shortCode";
                }
                if (type==2){
                    for (CustomerEntity p:list){
                        if (!p.getId().equals(id)){
                            return "shortCode";
                        }
                    }
                }
            }

        }

        return "";
    }

    /**
     * 获取所有用户
     * @return
     */
    @RequestMapping(value = "getusers",method = RequestMethod.POST)
    @ResponseBody
    public R<List<UserEntity>> getusers(){
        try {
            UserEntityExample example=new UserEntityExample();
            example.createCriteria();
            List<UserEntity> userEntities = userService.selectByExample(example);
            return R.build(userEntities);
        } catch (Exception e){
        e.printStackTrace();
        return R.buildError(ResultStatusEnum.ERROR);
        }
    }
    /**
     * 获取所有用户
     * @return
     */
    @RequestMapping(value = "getAllUser")
    @ResponseBody
    public R<List<UserEntity>> getAllUser(){
        try {
            UserEntityExample example=new UserEntityExample();
            example.createCriteria();
            List<UserEntity> userEntities = userService.selectByExample(example);
            return R.build(userEntities);
        } catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 分层获取客户信息
     * @return
     */
    @RequestMapping(value = "getAllCustomer")
    @ResponseBody
    public R<Map<String,Object>> getAllCustomer(Integer type, Integer lx){
        return R.build(customerService.getAllCustomer(type,lx ));
    }
    private boolean isAdmin( UserEntity user){
         // if(usercode.indexOf("admin") !=-1)
       return user.getRoles().indexOf("admin") !=-1 || user.getCode().equals("admin");
        //return false;
    }

    /**
     * 判断是否是管理员
     * @return
     */
    @RequestMapping(value = "isGLY")
    @ResponseBody
    public R<Boolean> isGLY(){
        try{
            UserEntity user = (UserEntity)this.getBean("user");
            boolean tf=isAdmin(user);
            return R.build(tf);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 根据code获取id
     * @param code
     * @return
     */
    @RequestMapping(value = "getIdBycode")
    @ResponseBody
    public  R<Integer> getIdBycode(String code){
        try{
           /* CustomerExample example=new CustomerExample();
            CustomerExample.Criteria criteria = example.createCriteria();
            criteria.andCodeLike("%"+code+"%");
            List<CustomerEntity> customerEntities = customerService.selectByExample(example);*/
            CustomerEntity ce=new CustomerEntity();
            ce.setCode(code);
            List<CustomerEntity> customerEntities =customerService.selectByMap2(ce);
           Integer id=0;
           if(customerEntities.size()>0){
               id=customerEntities.get(0).getId();
           }
            return R.build(id);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 保存转移
     * @param salesmanCode 业务员棉麻
     * @param codes 客户编码
     * @return
     */
    @RequestMapping(value = "saveTransfer",method = RequestMethod.POST)
    @ResponseBody
    public R<Boolean> saveTransfer(String salesmanCode,String[] codes ){
        try{
            int num=0;
            for(int i=0;i<codes.length;i++){
                String code=codes[i].replace("[","").replace("]","").replace("\"","");
                num=customerService.updateCustomerSal(salesmanCode,code);
            }
            return R.build(num >0?true:false);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }
    /**
     * 保存共享客户
     * @param usercode
     * @param codes
     * @return
     */
    @RequestMapping(value = "saveshare",method = RequestMethod.POST)
    @ResponseBody
    public R<Boolean> saveshare(String usercode,String[] codes ){
        try{
            int num=0;
            CustomerShareEntity record=new CustomerShareEntity();
            record.setUsercode(usercode);
            for(int i=0;i<codes.length;i++){
                String code=codes[i].replace("[","").replace("]","").replace("\"","");
                record.setCode(code);
                record.setType(1);
                num=customerShareService.insertSelective(record);
            }

            return R.build(num >0?true:false);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 根据客户编码查询客户共享
     * @param code
     * @return
     */
    @RequestMapping(value = "getSharedByCustomerCode" )
    @ResponseBody
    public R getSharedByCustomerCode(String code){
        try{
            CustomerShareExample example= new CustomerShareExample();
            CustomerShareExample.Criteria criteria = example.createCriteria();
            criteria.andCodeEqualTo(code);
            criteria.andTypeEqualTo(1);
            List<CustomerShareEntity> customerShareEntities = customerShareService.selectByExample(example);
            String sharecode="";
            for(int i=0;i<customerShareEntities.size();i++){
                CustomerShareEntity cse=customerShareEntities.get(i);
                sharecode=sharecode+cse.getUsercode()+",";
            }
            if(!sharecode.equals("")){
                sharecode=sharecode.replace("\"","");
                sharecode=sharecode.substring(0,sharecode.length()-1);
            }
            return R.build( sharecode);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }
    private String getcodes(String usercode){
        String obj="''";
        //不是管理员
            CustomerShareExample example=new CustomerShareExample();
            CustomerShareExample.Criteria criteria = example.createCriteria();
            criteria.andUsercodeEqualTo(usercode);
            criteria.andTypeEqualTo(1);
            List<CustomerShareEntity> customerShareEntities = customerShareService.selectByExample(example);
            for(int i=0;i<customerShareEntities.size();i++){
                obj+=",'"+customerShareEntities.get(i).getCode()+"'";
            }

        return  obj;
    }

    /**
     * 发起审批工作流
     * @return
     */
    @RequestMapping(value = "startProcess")
    @ResponseBody
    public R<String> startProcess(Integer id){
        try {
            UserEntity user = (UserEntity)this.getBean("user");
            UserEntityExample example=new UserEntityExample();
            UserEntityExample.Criteria criteria = example.createCriteria();
            criteria.andRolesLike("%kybzr%");
            List<UserEntity> userEntities = userService.selectByExample(example);
          //  List<String> list=new ArrayList<>();
            String hxspr="";
            for(int i=0;i<userEntities.size();i++){
                if(i==userEntities.size()-1){
                    hxspr+=userEntities.get(i).getCode();
                }else{
                    hxspr+=userEntities.get(i).getCode()+",";
                }

            }
            Map<String ,Object> map =new HashMap<>();
            map.put("kybzr",hxspr);
            String processid = ProcessService.startProcess("customer",id+"",map,user.getCode());
            CustomerEntity re=new CustomerEntity();
            re.setId(id);
            re.setSpstatus("1");
            customerService.updateByPrimaryKeySelective(re);
            ProcessCustomerEntity record=new ProcessCustomerEntity();
            record.setCustomerid(id);
            record.setProcessid(processid);
            int num = processCustomerService.insert(record);
            return R.build(processid);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }
    /**
     * 根据所属业务员编码获陬所有客户名称和编码
     *
     * @return
     */
    @RequestMapping(value = "getCustomer" ,method = RequestMethod.POST)
    @ResponseBody
    public R getCustomer(String codes) {
        try {
            List<String> list=new ArrayList<>();
            String[] split = codes.split(",");
            for(int i=0;i<split.length;i++){
                list.add(split[i]);
            }
            CustomerExample example = new CustomerExample();
            CustomerExample.Criteria criteria = example.createCriteria();
            criteria.andSalesmanIn(list);
            List<CustomerEntity> customerEntities = customerService.selectByExample(example);
            List<Map<String,String>> li=new ArrayList<>();
            for(int i=0;i<customerEntities.size();i++){
                CustomerEntity ce=customerEntities.get(i);
                Map<String,String> map=new HashMap<>();
                map.put(ce.getCode(),ce.getName());
                li.add(map);
            }
            return R.build(li);
        } catch (Exception e) {
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }
    @RequestMapping(value = "getcodeByname")
    @ResponseBody
    public R<List<String>> getcodeByname(String name){
        try {
            CustomerExample example = new CustomerExample();
            CustomerExample.Criteria criteria = example.createCriteria();
            criteria.andNameLike("%"+name+"%");
            List<CustomerEntity> customerEntities = customerService.selectByExample(example);
            List<String> list=new ArrayList<>();
            int num=0;
            if(customerEntities.size()>10){
                num=10;
            }else{
                num=customerEntities.size();
            }
            for(int i=0;i<num;i++){
                CustomerEntity ce=customerEntities.get(i);
                list.add(ce.getCode());
            }
            return R.build(list);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }

    }
    @RequestMapping(value = "getUsercodeByname")
    @ResponseBody
    public R<List<String>> getUsercodeByname(String name){
        try {
            UserEntityExample example=new UserEntityExample();
            UserEntityExample.Criteria criteria = example.createCriteria();
            criteria.andNameLike("%"+name+"%");
            List<UserEntity> userEntities = userService.selectByExample(example);
            List<String> list=new ArrayList<>();
            for(UserEntity ce:userEntities){
                list.add(ce.getCode());
            }
            return R.build(list);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }

    }

    /**
     * 未联系自动加入公共池
     * N天未联系的潜在客户加入公共池（最后一次发邮件的日期）
     * 原来的业务员赋值给创建人，并置空原来的业务员
     * @param type 客户类型
     * @param days 天数
     * @param poolType 公共池类型
     * @return
     */
    @RequestMapping(value = "insertAutoPoolSet")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public R  insertAutoPoolSet(String type,Integer days,Integer poolType) {
        try {
//            UserEntity user = (UserEntity)this.getBean("user");
//
//            CustomerExample example = new CustomerExample();
//            CustomerExample.Criteria criteria = example.createCriteria();
//            criteria.andTypeEqualTo(type);
//            criteria.andSalesmanIsNotNull();
//            criteria.andSalesmanIsNotNullStr();
//            List<CustomerEntity> customerEntities = customerService.selectByExample(example);
//            System.out.println("查询到的客户，总共"+ customerEntities.size() +"条");
//            int i=0;
//            //循环客户集合
//            for (CustomerEntity p:customerEntities){
//                System.out.println("执行到第"+ ++i +"条");
//                //业务员的邮件
//                UserEntity userEntity = userService.selectUserByCode(p.getSalesman());
//                String userEmail = userEntity.getEmail();
//                //客户联系人
//                CustomerContactExample contactExample=new CustomerContactExample();
//                CustomerContactExample.Criteria contactCriteria = contactExample.createCriteria();
//                contactCriteria.andCompanyEqualTo(p.getCode());
//                List<CustomerContactEntity> contactEntityList = customerContactService.selectByExample(contactExample);
//
//                if (!CollectionUtils.isEmpty(contactEntityList)){
//                    //客户联系人的邮件集合
//                    List<String> emailCollect = contactEntityList.stream().map(g -> g.getEmail()).distinct().collect(Collectors.toList());
//                    //业务员的邮箱和 客户联系人的邮箱都不为空
//                    if (userEmail!=null && !CollectionUtils.isEmpty(emailCollect)){
//                        //只需要业务员接收的最大时间 和业务员发送的最大时间。这两个时间比较得到最大时间，用这个时间和当前时间去比较
//
//                        //业务员是发件人 客户联系人是收件人，获取到业务员发送邮件的时间集合
//                        List<String> maxSendDateCollect=null;
//                        for (String g:emailCollect) {
//                            email_email email=new email_email();
//                            email.setSenderAddresser(userEmail);
//                            email.setRecipientAddress(g);
//                            List<email_email> sendEmailList = emailService.selectEmailByParam(email);
//                            maxSendDateCollect = sendEmailList.stream().map(h -> h.getSendDate()).collect(Collectors.toList());
//                        }
//
//
//                        //业务员收件人 客户联系人是发件人，获取到业务员接收邮件的时间集合
//                        List<String> maxRecdDateCollect=null;
//                        for (String g:emailCollect) {
//                            email_email email=new email_email();
//                            email.setSenderAddresser(g);
//                            email.setRecipientAddress(userEmail);
//                            List<email_email> recEmailList = emailService.selectEmailByParam(email);
//                            maxRecdDateCollect = recEmailList.stream().map(h -> h.getRecDate()).collect(Collectors.toList());
//
//                        }
//                        //邮件往来
//                        if (!CollectionUtils.isEmpty(maxSendDateCollect) && !CollectionUtils.isEmpty(maxRecdDateCollect)){
//                            //业务员发送的最大时间
//                            Date maxSendDate = DateUtils.convertStringToDate(Collections.max(maxSendDateCollect), DateUtils.DATE_TIME_PATTERN);
//                            //业务员接收的最大时间
//                            Date maxRecdDate = DateUtils.convertStringToDate(Collections.max(maxRecdDateCollect), DateUtils.DATE_TIME_PATTERN);
//
//                            String plusDay=null;
//                            if (maxSendDate.compareTo(maxRecdDate)>=0){
//                                //maxSendDate
//                                plusDay = DateUtils.plusDay(days, maxSendDate);
//                            }else{
//                                //maxRecdDate
//                                plusDay = DateUtils.plusDay(days, maxRecdDate);
//                            }
//                            Date maxDate=DateUtils.convertStringToDate(plusDay,DateUtils.DATE_TIME_PATTERN);
//                            //如果maxDate大于等于当前时间则不用加入公共池 否则加入公共池
//                            if (maxDate.compareTo(new Date())<0){
//                                //修改客户
//                                customerService.updateCustomerByParam(p);
//
//                                CustomerLogEntity log=new CustomerLogEntity();
//                                log.setCode(p.getCode());
//                                log.setType("加入公共池");
//                                log.setOptioner(user.getCode());
//                                log.setOptionTime(DateUtils.format(new Date()));
//                                log.setContent("加入公共池，客户编码："+p.getCode()+"，公共池类型：未联系自动加入公共池"+"，未联系天数："+days+"，原业务员编号："+p.getSalesman()+"，原创建人编号："+p.getCreater());
//                                customerLogService.insert(log);
//                            }
//                        }
//
//                    }
//                }
//                System.out.println("第"+ i +"条执行完成");
//            }
//
//            CustomerAutoPool record=new CustomerAutoPool();
//            record.setType(type);
//            record.setDays((long)days);
//            record.setPoolType(poolType);
//            customerAutoPoolService.insertSelective(record);
            return R.build(ResultStatusEnum.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }

    }


    /**
     * 未成单客户自动加入公共池
     * 第一次（min）邮件往来后，N天没有创建过外销单的潜在客户加入公共池
     * 原来的业务员赋值给创建人，并置空原来的业务员
     * @param type 客户类型
     * @param days 天数
     * @param poolType 公共池类型
     * @return
     */
    @RequestMapping("potentialCustomerNotExport")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public R potentialCustomerNotExport(String type,Integer days,Integer poolType){
        try {
//            UserEntity user = (UserEntity)this.getBean("user");
//
//            CustomerExample example = new CustomerExample();
//            CustomerExample.Criteria criteria = example.createCriteria();
//            criteria.andTypeEqualTo(type);
//            criteria.andSalesmanIsNotNull();
//            criteria.andSalesmanIsNotNullStr();
//            List<CustomerEntity> customerEntities = customerService.selectByExample(example);
//            for (CustomerEntity p:customerEntities){
//
//                //业务员的邮件
//                UserEntity userEntity = userService.selectUserByCode(p.getSalesman());
//                String userEmail = userEntity.getEmail();
//                //客户联系人
//                CustomerContactExample contactExample=new CustomerContactExample();
//                CustomerContactExample.Criteria contactCriteria = contactExample.createCriteria();
//                contactCriteria.andCompanyEqualTo(p.getCode());
//                List<CustomerContactEntity> contactEntityList = customerContactService.selectByExample(contactExample);
//
//                if (!CollectionUtils.isEmpty(contactEntityList)){
//                    //客户联系人的邮件集合
//                    List<String> emailCollect = contactEntityList.stream().map(g -> g.getEmail()).distinct().collect(Collectors.toList());
//                    //业务员的邮箱和 客户联系人的邮箱都不为空
//                    if (userEmail!=null && !CollectionUtils.isEmpty(emailCollect)){
//                        //只需要业务员接收的最大时间 和业务员发送的最大时间。这两个时间比较得到最大时间，用这个时间和当前时间去比较
//
//                        //业务员是发件人 客户联系人是收件人，获取到业务员发送邮件的时间集合
//                        List<String> maxSendDateCollect=null;
//                        for (String g:emailCollect) {
//                            email_email email=new email_email();
//                            email.setSenderAddresser(userEmail);
//                            email.setRecipientAddress(g);
//                            List<email_email> sendEmailList = emailService.selectEmailByParam(email);
//                            maxSendDateCollect = sendEmailList.stream().map(h -> h.getSendDate()).collect(Collectors.toList());
//                        }
//
//                        //业务员收件人 客户联系人是发件人，获取到业务员接收邮件的时间集合
//                        List<String> maxRecdDateCollect=null;
//                        for (String g:emailCollect) {
//                            email_email email=new email_email();
//                            email.setSenderAddresser(g);
//                            email.setRecipientAddress(userEmail);
//                            List<email_email> recEmailList = emailService.selectEmailByParam(email);
//                            maxRecdDateCollect = recEmailList.stream().map(h -> h.getRecDate()).collect(Collectors.toList());
//
//                        }
//                        //邮件往来
//                        if (!CollectionUtils.isEmpty(maxSendDateCollect) && !CollectionUtils.isEmpty(maxRecdDateCollect)) {
//                            //业务员发送的最小时间
//                            Date mimSendDate = DateUtils.convertStringToDate(Collections.min(maxSendDateCollect), DateUtils.DATE_TIME_PATTERN);
//                            //业务员接收的最小时间
//                            Date mimRecdDate = DateUtils.convertStringToDate(Collections.min(maxRecdDateCollect), DateUtils.DATE_TIME_PATTERN);
//
//                            String plusDay = null;
//                            if (mimSendDate.compareTo(mimRecdDate) <= 0) {
//                                plusDay = DateUtils.plusDay(days, mimSendDate);
//                            } else {
//                                plusDay = DateUtils.plusDay(days, mimRecdDate);
//                            }
//                            Date minDate = DateUtils.convertStringToDate(plusDay, DateUtils.DATE_TIME_PATTERN);
//                            //如果maxDate大于等于当前时间则不用加入公共池 否则加入公共池
//                            if (minDate.compareTo(new Date()) < 0) {
//                                List<ExportContractEntity> contractList = exportContractService.findExportContractByParam(p.getCode());
//                                //未成单客户
//                                if (CollectionUtils.isEmpty(contractList)){
//                                    //修改客户
//                                    customerService.updateCustomerByParam(p);
//                                    CustomerLogEntity log = new CustomerLogEntity();
//                                    log.setCode(p.getCode());
//                                    log.setType("加入公共池");
//                                    log.setOptioner(user.getCode());
//                                    log.setOptionTime(DateUtils.format(new Date()));
//                                    log.setContent("加入公共池，客户编码：" + p.getCode() + "，公共池类型：联系未成单客户加入公共池" + "，未成单天数：" + days + "，原业务员编号：" + p.getSalesman() + "，原创建人编号：" + p.getCreater());
//                                    customerLogService.insert(log);
//                                }
//
//                            }
//                        }
//                    }
//                }
//            }
//
//            CustomerAutoPool record=new CustomerAutoPool();
//            record.setType(type);
//            record.setDays((long)days);
//            record.setPoolType(poolType);
//            customerAutoPoolService.insertSelective(record);
            return R.build(ResultStatusEnum.SUCCESS);
        } catch (Exception e) {
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
    }

    /**
     * 距上次成单客户加入公共池
     * 距最近创建过外销单的合作客户（max），N天内没有再次创建外销的客户 加入公共池
     * 原来的业务员赋值给创建人，并置空原来的业务员
     * @param type 客户类型
     * @param days 天数
     * @param poolType 公共池类型
     * @return
     */
    @RequestMapping("potentialCustomerLastExport")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public R potentialCustomerLastExport(String type,Integer days,Integer poolType){
        try {
//            UserEntity user = (UserEntity)this.getBean("user");
//
//            CustomerExample example = new CustomerExample();
//            CustomerExample.Criteria criteria = example.createCriteria();
//            criteria.andTypeEqualTo(type);
//            criteria.andSalesmanIsNotNull();
//            criteria.andSalesmanIsNotNullStr();
//            List<CustomerEntity> customerEntities = customerService.selectByExample(example);
//            for (CustomerEntity p:customerEntities){
//
//                List<ExportContractEntity> contractList = exportContractService.findExportContractByParam(p.getCode());
//                if (!CollectionUtils.isEmpty(contractList)){
//                    //获取外销创建时间集合
//                    List<Date> createDateList = contractList.stream().map(g -> g.getCreateDate()).distinct().collect(Collectors.toList());
//                    if (!CollectionUtils.isEmpty(createDateList)){
//                        //获取最大日期并加上指定天数
//                        String plusDay =  DateUtils.plusDay(days, Collections.max(createDateList));
//                        Date maxDate = DateUtils.convertStringToDate(plusDay, DateUtils.DATE_TIME_PATTERN);
//                        //如果maxDate大于等于当前时间则不用加入公共池 否则加入公共池
//                        if (maxDate.compareTo(new Date())<0){
//                            //修改客户
//                            customerService.updateCustomerByParam(p);
//                            CustomerLogEntity log = new CustomerLogEntity();
//                            log.setCode(p.getCode());
//                            log.setType("加入公共池");
//                            log.setOptioner(user.getCode());
//                            log.setOptionTime(DateUtils.format(new Date()));
//                            log.setContent("加入公共池，客户编码：" + p.getCode() + "，公共池类型：距上次成单客户加入公共池" + "，未成单天数：" + days + "，原业务员编号：" + p.getSalesman() + "，原创建人编号：" + p.getCreater());
//                            customerLogService.insert(log);
//                        }
//                    }
//
//                }
//            }
//
//            CustomerAutoPool record=new CustomerAutoPool();
//            record.setType(type);
//            record.setDays((long)days);
//            record.setPoolType(poolType);
//            customerAutoPoolService.insertSelective(record);
            return R.build(ResultStatusEnum.SUCCESS);

//            //客户距上次成单days天未成单加入公共池
//            customerService.potentialCustomerLastExport(type,days);
//            return R.build(ResultStatusEnum.SUCCESS);
        } catch (Exception e) {
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
    }


    @RequestMapping(value = "getPoolData" )
    @ResponseBody
    public R<List<CustomerAutoPool>>  getPoolData(Integer poolType) {
        try {
            CustomerAutoPoolExample example=new CustomerAutoPoolExample();
            CustomerAutoPoolExample.Criteria criteria=example.createCriteria();
            criteria.andPoolTypeEqualTo(poolType);
            List<CustomerAutoPool> customerAutoPools = customerAutoPoolService.selectByExample(example);
            return R.build(customerAutoPools);

        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }

    }
    @RequestMapping(value = "test")
    @ResponseBody
    public void test(){
       /* UserEntity user = (UserEntity)this.getBean("user");
        customerService.getHZ30And60Days(user);*/
        List<String> list=new ArrayList<>();
        list.add("joy.yu@fengqish.com");
        list.add("lishar_shen@fengqish.cofalse");
        customerService.getMapByEmail(list);
    }

    /**
     * 获取当前用户所管理 （及其所管理员工）的客户联系人信息
     * @return
     */
    @RequestMapping(value = "queryConTactByUserCode")
    @ResponseBody
    public R<Map<String,Object>> queryConTactByUserCode(){
        try {
            UserEntity user = (UserEntity)this.getBean("user");
            Map<String, Object> stringObjectMap = customerService.queryConTactByUserCode(user);
            return R.build(stringObjectMap);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }

    }

    /**
     * 获取所有客户
     * @return
     */
    @RequestMapping("getCustomer")
    @ResponseBody
    public R getCustomer(){
        try {
            List<CustomerEntity> customer= customerService.selectByExample(null);
            return R.build(customer);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 更新客户的 账期,信用额度,成单日期
     * @param customerCode 客户编号
     * @param accountPeriod 账期
     * @param creditLine 信用额度
     * @param orderDate 成单日期
     * @param attributesOfCustomers 客户属性
     * @return
     */
    @RequestMapping("updateCustomerInfo")
    @ResponseBody
    public R updateCustomerInfo(String customerCode,String accountPeriod,String creditLine,String orderDate,String attributesOfCustomers){
        try {
            CustomerEntity customerEntity=customerService.findCustomerByCode(customerCode);
            int num=0;
            if (customerEntity!=null){
                customerEntity.setAccountPeriod(accountPeriod);
                customerEntity.setCreditLine(creditLine);
                customerEntity.setOrderDate(DateUtils.convertStringToDate(orderDate,DateUtils.DATE_PATTERN));
                customerEntity.setAttributesOfCustomers(attributesOfCustomers);
                num = customerService.updateByPrimaryKeySelective(customerEntity);

            }
            if (num==1){
                return R.build(ResultStatusEnum.SUCCESS);
            }else {
                return R.buildError(ResultStatusEnum.ERROR);
            }

        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     *
     * @param customerAndEmail
     * @return
     */
    @RequestMapping(value = "selectEmailCustomByDim",method = RequestMethod.GET)
    @ResponseBody
    public R<List<String>> selectEmailCustomByDim( CustomerAndEmail customerAndEmail){
        List<String> userListByCode=new ArrayList<>();
        List<String> reuserListByCode=new ArrayList<>();
        try {

            userListByCode = customerService.selectEmailCustomByDim(customerAndEmail);
            for(String s:userListByCode){
                s=s.replaceAll("<","&lt;");
                s=s.replaceAll(">","&gt;");
                reuserListByCode.add(s);
            }

            R<List<String>> build = R.build(reuserListByCode);
            build.setCode(200);
            return build;
        }catch (Exception e){
            e.printStackTrace();
            return R.build(userListByCode);
        }
    }
    @RequestMapping(value = "selectEmailCustomConCateByCode",method = RequestMethod.POST)
    @ResponseBody
    public R<List<Map<String,Object>>> selectEmailCustomConCateByCode(@RequestParam(value = "code") String code){
    /*@RequestMapping(value = "selectEmailCustomConCateByCode",method = RequestMethod.GET)
    @ResponseBody
    public R<List<Map<String,Object>>> selectEmailCustomConCateByCode(  String code){*/
        List<Map<String,Object>> list=new ArrayList<>();
        try {
            list=customerService.selectEmailCustomConCateByCode(code);
            return R.build(list);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }

    }

    /**
     * 客户信息记录统计--分页
     * @param req
     * @return
     */
    @RequestMapping("customerInfoListByPage")
    @ResponseBody
    public R getCustomerInfoListByPage(CustomerInformationRecordReq req){
        try {
            PageInfo<CustomerInformationRecordRes> pageInfo= customerService.getCustomerInfoList(req);
            return R.build(0,"",pageInfo.getTotal(),pageInfo.getList());
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }
    /**
     * 客户信息记录统计--导出
     * @param req 入参实体
     * @return
     */
    @RequestMapping("customerInfoListExport")
    @ResponseBody
    public R customerInfoListExport(CustomerInformationRecordReq req) {
        try {
            JSONObject info = customerService.customerInfoListExport(req);
            return R.build(info);
        } catch (Exception e) {
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
    }

    /**
     *
     * @param text  内容信息
     * @param zd   是哪个字段
     * @return
     */
    @GetMapping("isExist")
    @ResponseBody
    public  R isExist(String text,String zd,String id){
        String message="";
        try {

                message = customerService.isExist(text, zd,id);

             //System.out.println(text+"###3"+zd);

            return R.build(message);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }


    /**
     * 新客户账期详情统计-分页
     * @return
     */
    @RequestMapping("customerBillingPeriodListByPage")
    @ResponseBody
    public R customerBillingPeriod(CustomerBillingPeriodReq req){
        try {
            PageInfo<CustomerBillingPeriodRes> pageInfo= customerService.customerBillingPeriod(req);
            return R.build(0,"",pageInfo.getTotal(),pageInfo.getList());
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
    * 新客户账期详情统计--导出
    * @param req 入参实体
    * @return
    */
    @RequestMapping("customerBillingPeriodExport")
    @ResponseBody
    public R customerBillingPeriodExport(CustomerBillingPeriodReq req) {
        try {
            JSONObject info = customerService.customerBillingPeriodExport(req);
            return R.build(info);
        } catch (Exception e) {
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
    }


    /**
     * 客户下单出货记录统计-分页
     * @return
     */
    @RequestMapping("customerOrderAndShipInfoListByPage")
    @ResponseBody
    public R customerOrderAndShipInfoListByPage(CustomerOrderAndShipInfoReq req){
        try {
            PageInfo<CustomerOrderAndShipInfoRes> pageInfo= customerService.customerOrderAndShipInfo(req);
            return R.build(0,"",pageInfo.getTotal(),pageInfo.getList());
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }
    /**
     * 客户下单出货记录统计--导出
     * @param req 入参实体
     * @return
     */
    @RequestMapping("customerOrderAndShipInfoExport")
    @ResponseBody
    public R customerOrderAndShipInfoExport(CustomerOrderAndShipInfoReq req) {
        try {
            JSONObject info = customerService.customerOrderAndShipInfoExport(req);
            return R.build(info);
        } catch (Exception e) {
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
    }
    /**
     * 判断当前登录用户是否为 营销部门的总监 角色
     * @return
     */
    @RequestMapping("isMarketingDirector")
    @ResponseBody
    public R isMarketingDirector(){
        try {
            String isMarketingDirector="";
            UserEntity user = (UserEntity) this.getBean("user");
            String roles = user.getRoles();
            if (roles.contains("YXZJ003")){
                return R.build(true);
            }
            return R.build(false);
        } catch (Exception e) {
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
    }

    /**
     * 判断当前用户是否为管理员
     * @return
     */
    @RequestMapping("isAdmin")
    @ResponseBody
    public R isAdmin(){
        try {
            UserEntity user = (UserEntity) this.getBean("user");
            String roles = user.getRoles();
            if (roles.contains("admin")){
                return R.build(true);
            }
            return R.build(false);
        } catch (Exception e) {
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
    }

    /**
     * 判断当前用户是否包含物流主管角色
     * @return true:是 false:否
     */
    @RequestMapping("isLogisticsSupervisor")
    @ResponseBody
    public R isLogisticsSupervisor(){
        try {
            UserEntity user = (UserEntity) this.getBean("user");
            String roles = user.getRoles();
            if (roles.contains("WLZG008")){
                return R.build(true);
            }
            return R.build(false);
        } catch (Exception e) {
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
    }

    /**
     * 判断当前用户是否是：采购主管、管理员、产品中心、财务
     * @return
     */
    @RequestMapping("isPurchaseAdmin")
    @ResponseBody
    public R isPurchaseAdmin(){
        try {
            UserEntity user = (UserEntity) this.getBean("user");
            String roles = user.getRoles();
            if (roles.contains("CGZG001") || roles.contains("admin") || roles.contains("supplyChainCenter") || roles.contains("CW01")){
                return R.build(true);
            }
            return R.build(false);
        } catch (Exception e) {
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
    }

    /**
     * 判断当前用户是否是：研发主管、研发助理、管理员、财务、产品交付中心、品质经理
     * @return
     */
    @RequestMapping("isProductAdmin")
    @ResponseBody
    public R getIsProductAdmin(){
        try {
            UserEntity user = (UserEntity) this.getBean("user");
            String roles = user.getRoles();
            if (roles.contains("YFZG011") ||
                    roles.contains("YFZL012") ||
                    roles.contains("admin") ||
                    roles.contains("CW01") ||
                    roles.contains("supplyChainCenter") ||
                    roles.contains("PZJINGLI")){
                return R.build(true);
            }
            return R.build(false);
        } catch (Exception e) {
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
    }

    /**
     * 更改审批状态
     * @param id
     * @param spstatus
     * @return
     */
    @RequestMapping(value = "updateSpStatus" )
    @ResponseBody
    public R updateSpStatus( String id,String spstatus){
        try{
            CustomerEntity customerEntity = customerService.selectByPrimaryKey(Integer.parseInt(id));
            String oldSpStatus = customerEntity.getSpstatus();
            oldSpStatus=convertStatus(oldSpStatus);


            CustomerEntity record=new CustomerEntity();
            record.setId(Integer.parseInt(id));
            record.setSpstatus(spstatus);
            customerService.updateByPrimaryKeySelective(record);
            spstatus=convertStatus(spstatus);


            //日志
            UserEntity user = (UserEntity)this.getBean("user");
            if (spstatus.equals("待批箱")){
                addMessageSp(customerEntity,user);
            }

            CustomerLogEntity log=new CustomerLogEntity();
            log.setCode(customerEntity.getCode());
            log.setType("更新");
            log.setOptioner(user.getCode());
            log.setOptionTime(DateUtils.format(new Date()));
            log.setContent("客户编码："+customerEntity.getCode()+"，更新审批状态：从 "+oldSpStatus+" 更新为 "+spstatus);
            customerLogService.insert(log);

            return R.build(ResultStatusEnum.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 转换箱体
     * @param status
     * @return
     */
    private String convertStatus(String status){
        switch (status){
            case "1":
                status="草稿箱";
                break;
            case "2":
                status="待批箱";
                break;
            case "3":
                status="已批箱";
                break;
            case "4":
                status="完成箱";
                break;
            case "5":
                status="垃圾箱";
                break;
        }
        return status;
    }

    /**
     * 更改客户类型
     * @param id
     * @param type
     * @return
     */
    @RequestMapping(value = "updateCustomerType" )
    @ResponseBody
    public R updateCustomerType( String id,String type){
        try{
            CustomerEntity record=new CustomerEntity();
            record.setId(Integer.parseInt(id));
            record.setType(type);
            customerService.updateByPrimaryKeySelective(record);

            return R.build(ResultStatusEnum.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 更新授信
     * @param ids
     * @param isCredit
     * @return
     */
    @RequestMapping(value = "updateCredit" )
    @ResponseBody
    public R updateCredit(String[] ids,String isCredit){
        try{
            UserEntity user = (UserEntity)this.getBean("user");

            List<Integer> list=new ArrayList<>();
            for(int i=0;i<ids.length;i++){
                list.add(Integer.parseInt(ids[i].replace("[","").replace("]","")));
            }
            CustomerExample example=new CustomerExample();
            CustomerExample.Criteria criteria = example.createCriteria();
            criteria.andIdIn(list);
            List<CustomerEntity> customerEntities = customerService.selectByExample(example);

            for (CustomerEntity p:customerEntities){
                p.setIsCredit(isCredit);
                customerService.updateByPrimaryKeySelective(p);

                //添加消息
                if (isCredit.equals("1") && p.getAccountPeriod().equals("0")){
                    addMessageSx(p,user);
                }

            }

            return R.build(ResultStatusEnum.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 新增消息
     * 授信状态为1 账期为0 添加到消息表，接收人为 RKB004
     */
    public void addMessageSx(CustomerEntity record, UserEntity user) throws ParseException {
        EditMessageReq req=new EditMessageReq();
        req.setTheme("客户授信");
        req.setReceiverCode("RKB004");
        req.setMessageType(4);
        req.setContent("客户名称为："+record.getName()+
                "，客户简码为："+record.getShortCode()+
                "，客户编码为："+record.getCode()+
                "，客户简称为："+record.getAbbreviation()+
                "，账期为：0");
        messageAllService.editMessage(req,user.getName(),user.getCode());
    }

    /**
     * 查询授信状态为1 账期为0 的客户
     * @return
     */
    @RequestMapping(value = "getCreditCustomerList" )
    @ResponseBody
    public R getCreditCustomerList(){
        try{
            CustomerExample example = new CustomerExample();
            CustomerExample.Criteria criteria = example.createCriteria();
            criteria.andIsCreditEqualTo("1");
            criteria.andAccountPeriodEqualTo("0");
            List<CustomerEntity> list = customerService.selectByExample(example);
            return R.build(list);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }


    /**
     * 根据名称查询 指定条件的客户列表
     * @return
     */
    @RequestMapping(value = "getCustomerByParamList" )
    @ResponseBody
    public R getCustomerByParamList(String name){
        try{
            List<DictionaryEntity> dictionaryList = dictionary2Service.getValue(6, 27);
            List<DictionaryEntity> collect = dictionaryList.stream().filter(p -> p.getName().indexOf("合作",0) == 0).collect(Collectors.toList());
            List<String> codeList = collect.stream().map(p -> p.getCode()).collect(Collectors.toList());

            CustomerExample example = new CustomerExample();
            CustomerExample.Criteria criteria = example.createCriteria();
            criteria.andNameLike("%"+name+"%");
            criteria.andSalesmanIsNotNull();
            criteria.andSalesmanIsNotNullStr();
            criteria.andTypeIn(codeList);
            criteria.andStatusNotEqualTo("B");


            CustomerExample.Criteria criteria2 = example.createCriteria();
            criteria2.andNameLike("%"+name+"%");
            criteria2.andSalesmanIsNotNull();
            criteria2.andSalesmanIsNotNullStr();
            criteria2.andTypeIn(codeList);
            criteria2.andStatusIsNull();

            example.or(criteria2);

            List<CustomerEntity> list = customerService.selectByExample(example);


            return R.build(list);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }
}
